<?php
/**
 * 拍卖服务逻辑：
 * 1、计算离最近00、10、20、30、40、50结尾的分钟时间还有多少秒
 * 2、用这个秒来设置sleep时间
 * 3、取得有当前时间是否有拍卖场次，如果没有则sleep 60 秒再跳到第1步，如果有进入第4步
 * 4、把当前场次<paimai_special>的starttime=now(),state=1
 * 5、取得当前场次的要拍卖的车源列表，seq desc排序
 * 6、如果没有记录跳到8步，如果有记录进入第7步
 * 7、循环这个拍卖列表，从第一条开始，update paimai_special_car set starttime=now(), state=1然后 sleep(120)再执行拍卖结算函数
 * 8、循环结束执行场次结束函数 
 * 9、跳入第一步
 * 
 */
#error_reporting ( 0 );
date_default_timezone_set ( "Asia/Shanghai" );
set_time_limit ( 0 );
if (isset ( $_SERVER ['REQUEST_URI'] )) {
	die ( 'error' );
}
if (! defined ( 'API_ROOT_PATH' )) {
	define ( 'API_ROOT_PATH', dirname ( __FILE__ ) );
}


require_once (API_ROOT_PATH . '/inc/Config.php');
require_once (API_ROOT_PATH . '/inc/dblink.php');



$dbh = new dblink ( MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE );

function  getNextSleepSecond() {
    // $date1 = time();
    // $date2 = date('Y-m-d H:i:00',strtotime('+1 min',$date1));    
    // $date2 = strtotime($date2);
    // $s = $date2-$date1;    
    
    // $date1 = date('Y-m-d H:i:s',$date1);
    // $date2 = date('Y-m-d H:i:00',$date2);

    // print_r("currtime:$date1   nexttime:$date2   timediff:$s\n");

    // return $s;


	$strm = date("i");
	$date1 = date("Y-m-d H:i:s");
    $timediff = 10 - intval(substr($strm, strlen($strm)-1, strlen($strm)));	
	$date2 = date("Y-m-d H:i:00", strtotime("$date1 +$timediff min"));
	$s = strtotime($date2)-strtotime($date1);
	print_r("currtime:$date1   nexttime:$date2   timediff:$s\n");
	return $s;
}


function parseSpecial($res) {
    if ($res && is_array ( $res )) {
        $data = array("scene_id"        =>  $res["scene_id"],
                        "emp_id"        =>  $res["emp_id"],
                        "name"          =>  $res["name"],
                        "starttime"     =>  $res["starttime"],
                        "endtime"       =>  $res["endtime"],
                        "status"        =>  $res["status"],
                        "createtime"    =>  $res["createtime"]

        );

        return $data;
    } else {
        return NULL;
    }
}

/*********处理场次************/
//状态（1 待拍,2 拍卖中,3 完毕）
function getOrderScene ($strtime) {
    global $dbh;
    $sql = "select * from `au_order_scene` where `status`=1 and `starttime`='$strtime' limit 1";
    $res = $dbh->query ( $sql );

    return parseSpecial ( $res );
}

function sceneStart($id) {
    global $dbh;
    $sql = "update `au_order_scene` set `status`=2 where `scene_id`=$id";
    $dbh->execNonQuery($sql);
}

function sceneEnd($id) {
    global $dbh;
    $sql = "update `au_order_scene` set `status`=3, `endtime`=now() where `scene_id`=$id";
    $dbh->execNonQuery($sql);
}

function getOrderList($scene_id) {
    global $dbh;
    $sql = "select * from `au_order` where `scene_id`=$scene_id and `status`=3 order by `rank` asc";
    $res = $dbh->exec($sql);
    $data = array();
    if($res) {
        while($row = $dbh->fetch()) {
            array_push ($data, array("order_id"=>$row['order_id'],
                                    "est_elapsed_time"=>$row['est_elapsed_time']
                                )
                        );
        }
    }

    return $data;
}
/*********处理场次************/



/*********处理拍单************/
//拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8付付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功)]
function orderStart($id) {
    global $dbh;
    //$sql = "SELECT * FROM (SELECT price,dealer_id FROM au_bid_log WHERE order_id='{$id}' GROUP BY dealer_id ORDER BY createtime DESC) AS price ORDER BY price DESC LIMIT 0,1";
    $sql = "SELECT price,dealer_id FROM au_bid_log a INNER JOIN (SELECT MAX(bid_id) bid_id FROM au_bid_log WHERE order_id='{$id}' GROUP BY dealer_id) b ON a.`bid_id` = b.bid_id ORDER BY price DESC,createtime LIMIT 1;";
    echo $sql,"\n";
    $res = $dbh->query($sql);    
    $sql = "update `au_order` set bid_best_price='{$res['price']}',bid_best_dealer_id='{$res['dealer_id']}', `bidding_start_time`=now(), `status`=4 where `order_id`=$id";
    echo '记入投标最高车商:',$sql,"\n"; 
    $dbh->execNonQuery($sql);
        
    if($res['dealer_id']){
        $sql = "call paimai_refund('{$id}' , '{$res['dealer_id']}' );";
        echo '解冻投标阶段的保证金:',$sql,"\n";
        $dbh->execProcedureNonQuery($sql);
    }else{
        echo '无人投标!',"\n";
    }
}

function orderWaitBidding($ids) {
    $new_ids = array();
    foreach ($ids as $key => $row) {
        array_push($new_ids, $row['order_id']);
    }
    global $dbh;
    $new_ids = implode(',', $new_ids);      
    $sql = "update `au_order` set `status`=301 where `order_id` in ({$new_ids})";
    echo '拍单列表:',$new_ids,"\n";
    $dbh->execNonQuery($sql);
}

function getOrderTimes($id) {
    global $dbh;
    $sql = "select * from `au_order` where `order_id`=$id";
    $res = $dbh->query ( $sql );
    if($res) return $res['act_elapsed_time'];
    else return 0;
}

function orderEnd($id) {
    global $dbh;
    $sql = "call paimai_complete($id);";
    echo '拍单结束:',$sql,"\n";
    $dbh->execProcedureNonQuery($sql);
}
/*********处理拍单************/


//状态（1 待拍,2 拍卖中,3 完毕）


//$special_is_null_sleep = 60;
$special_is_null_sleep = 0;
$special_car_sleep = 120;
$special_car_sleep1 = 5;

while ( true ) {

	print_r ( "\n" );
	@ob_flush ();

    $sleeptimes = getNextSleepSecond();
    
    print_r("sleep:".$sleeptimes."\n");

	sleep ($sleeptimes);

    echo '查找',date("Y-m-d H:i:00"),'场',"\n";

	$special = getOrderScene(date("Y-m-d H:i:00"));

	if($special!=null) {
		// 专场拍卖开始
		print_r("\n\n\n");
		print_r("拍卖专场开始：[".date("Y-m-d H:i:s")."]".$special->name."\n");

        var_dump($special);
        sceneStart($special['scene_id']);

		/***********专场车源拍卖************/
		$carlist = getOrderList($special['scene_id']);
        orderWaitBidding($carlist);//把场所有拍单改成“待竞标”状态
		if(isset($carlist) && is_array($carlist)) {
			foreach($carlist as $item){
				if($item!=null) {
					// 单个车源拍卖开始
					print_r("拍卖车源开始[".date("Y-m-d H:i:s")."]：".$item['order_id']."\n");
                    orderStart($item['order_id']);

                    $special_car_sleep = $item["est_elapsed_time"];
					// 单个车源拍卖2分钟结束
					sleep ($special_car_sleep);

					/********处理拍卖延时**********/
					$overtime = true;
					$times = $special_car_sleep; //预计时长，（如：60）
					while($overtime) {
                        $_times = getOrderTimes($item['order_id']); // 真实要结束的时长
						if($_times>$times) {
							sleep($_times - $times);
							$times = $_times;
						} else {
							$overtime = false;
						}
					}
					/********处理拍卖延时**********/

                    // 单个车拍卖结束
                    orderEnd($item['order_id']);
                    print_r("拍卖车源结束[".date("Y-m-d H:i:s")."]：".$item['order_id']."\n");
                    // 结算完了在过5秒加入小一个车
                    sleep($special_car_sleep1);
				}
			}
		}
		/***********专场车源拍卖************/

		// 专场拍卖结束
        sceneEnd($special['scene_id']);
		print_r("拍卖专场结束：[".date("Y-m-d H:i:s")."]".$special['scene_id']."\n");
		print_r("\n\n\n");
	} else {
		print_r(date("Y-m-d H:i:s")."special is null\n");
		sleep($special_is_null_sleep);
	}
}